package terminal.model;

import java.util.ArrayList;
import terminal.interfaces.ILineListener;
import terminal.interfaces.IStringListener;

/**
 *
 * @author P. Podwapinski
 */
public class LineBuilder implements IStringListener
{
    public LineBuilder()
    {
        m_currentLine = new String();
        m_lineListeners = new ArrayList<>();
    }
    
    @Override public void onString( final String string )
    {
        if ( null != string )
        {
            final int nlPosition = string.indexOf( CHAR_NL );

            if ( -1 != nlPosition ) // There's a NL character, we need to notify and split
            {
                if ( 0 == nlPosition ) // NL as a first char
                {
                    notifyLineListeners( m_currentLine );

                    // Update
                    m_currentLine = string.substring( 1 );
                }
                else
                {
                    m_currentLine += string.substring( 0, nlPosition );
                    notifyLineListeners( m_currentLine );

                    // Update
                    m_currentLine = string.substring( nlPosition + 1 );
                }            
            }
            else // Just add characters to the current line
            {
                m_currentLine += string;            
            }                
        }        
    }
    
    public void addListener( ILineListener listener )
    {
        if ( null != listener )
        {
            m_lineListeners.add( listener );
        }
    }
    
    private void notifyLineListeners( final String line )
    {
        for ( ILineListener listener : m_lineListeners  ) 
        {
            if ( null != listener )
            {
                listener.onNewLine( line );
            }
        }         
    }    
    
    private static char CHAR_NL = '\r';
    private String m_currentLine;
    private ArrayList<ILineListener> m_lineListeners;    
}
